package com.flyco.modules.oms.handle.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flyco.common.util.HttpUtil;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.oms.entity.OmsOrderTrace;
import com.flyco.modules.oms.handle.ISyncLogisticsHandle;
import com.flyco.modules.oms.mapper.OmsOrderTraceMapper;
import com.flyco.modules.oms.model.OmsOrderZtoTraceModel;
import com.flyco.modules.oms.service.IOmsOrderAdditionService;
import com.flyco.modules.util.ApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.beans.BeanUtils;

import java.util.*;
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.stream.Collectors;

/**
 * 同步中通物流轨迹
 */
@Slf4j
@Component("logisticsHandle-中通")
@Primary
public class SyncLogisticsZtoHandleImpl implements ISyncLogisticsHandle {
    @Autowired
    private OmsOrderTraceMapper omsOrderTraceMapper;
    @Autowired
    private IOmsOrderAdditionService omsOrderAdditionService;

    @Override
    public void syncLogistics(String billcode, String orderId) {
        log.info("开始同步中通物流单号 :" + billcode);

        JSONArray billData = new JSONArray();
        billData.add(billcode);
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("data", billData.toJSONString());
        parameters.put("company_id", ApiUtil.getZtoCompanyId());
        parameters.put("msg_type", "NEW_TRACES");

        String strToDigest = paramsToQueryString(parameters) + ApiUtil.getZtoKey();
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        md.update(strToDigest.getBytes(Charset.forName("UTF-8")));
        String dataDigest = Base64.getEncoder().encodeToString(md.digest());

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        headers.put("x-datadigest", dataDigest);
        headers.put("x-companyid", ApiUtil.getZtoCompanyId());

        log.info("x-datadigest:" + dataDigest);
        log.info("x-companyid:" + ApiUtil.getZtoCompanyId());



        String result = HttpUtil.postRequest(ApiUtil.getZtoUrl(), headers, parameters);
        log.info("result:" + result);

        /*StringBuilder url = new StringBuilder();
        url.append(ApiUtil.getYundaUrl());
        url.append("query/json.php?partnerid=feikewuliu&mailno=");
        url.append(billcode);

        String result = HttpUtil.getRequest(url.toString());*/
        if (! oConvertUtils.isEmpty(result)) {
            JSONArray dataArray = JSON.parseObject(result).getJSONArray("data");
            for(int i=0; i<dataArray.size(); i++){
                JSONObject resultObj = dataArray.getJSONObject(i);
                String traceCode = resultObj.getString("billCode");
                JSONArray jsonArray = resultObj.getJSONArray("traces");
                log.info("jsonArray:" + jsonArray);
                if (null != jsonArray && jsonArray.size() > 0) {
                    List<OmsOrderZtoTraceModel> addModels = new ArrayList<>();
                    Integer dbCount = omsOrderTraceMapper.getCountByTraceNo(billcode);
                    List<OmsOrderZtoTraceModel> models = jsonArray.toJavaList(OmsOrderZtoTraceModel.class);
                    Collections.sort(models, Comparator.comparing(OmsOrderZtoTraceModel::getCreateTime));
                    if (jsonArray.size() > dbCount) {
                        addModels = models.subList(dbCount, models.size());
                    }
                    //log.info("addModels:" + addModels);
                    List<OmsOrderTrace> traces = new ArrayList<>();
                    for (OmsOrderZtoTraceModel traceModel : addModels) {
                        OmsOrderTrace trace = new OmsOrderTrace();
                        BeanUtils.copyProperties(traceModel, trace);
                        if ( oConvertUtils.isEmpty(trace.getContent()) ) {
                            trace.setContent( "【" + traceModel.getScanSite() + "】" + traceModel.getLabel() );
                        }
                        trace.setTraceNo(traceCode);
                        trace.setLabel(traceModel.getLabel());
                        omsOrderTraceMapper.insert(trace);
                    }

                    OmsOrderZtoTraceModel traceModel =  models.get(models.size() - 1);
                    String sign = "签收,SIGNED";
                    if(oConvertUtils.isNotEmpty(traceModel.getLabel()) && Arrays.asList(sign.split(",")).contains(traceModel.getLabel())) {
                        // TODO: 2020/4/8 处理订单签收
                        omsOrderTraceMapper.updateOrderSigned(orderId, billcode, traceModel.getCreateTime());

                        try {
                            omsOrderAdditionService.afterSign(orderId);
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }
                    }
                }
            }

        }
    }


    public static String paramsToQueryString(Map<String, Object> params) {
        return params.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
    }


    public static String paramsToQueryStringUrlencoded(Map<String, String> params) {
        return params.entrySet().stream().map(e -> {
            try {
                return e.getKey() + "=" + URLEncoder.encode(e.getValue(), "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                return e.getValue();
            }
        }).collect(Collectors.joining("&"));
    }
}
